package com.sx.manage.service.file;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sx.manage.biz.file.ICertificateAddressBiz;
import com.sx.manage.service.sys.IMBaseSystemConfigInfoService;
import com.sx.manage.servlet.ViewAndModel;
import com.sx.model.constants.MSystemConstants;
import com.sx.model.constants.type.consumer.MConsumersNatures;
import com.sx.model.manage.mybatis.form.file.MCertificateAddressForm;
import com.sx.model.manage.mybatis.form.sys.MSystemConfigInfoForm;
import com.sx.model.manage.mybatis.vo.consumer.login.MConsumerLoginVO;
import com.sx.model.manage.mybatis.vo.file.MCertificateAddressVO;
import com.sx.model.manage.mybatis.vo.result.ResultBooleanVO;
import com.sx.model.manage.mybatis.vo.result.ResultListVO;
import com.sx.model.manage.mybatis.vo.result.ResultUploadVO;
import com.sx.model.manage.mybatis.vo.sys.MSysConfigVO;

/**
 * 证件地址信息
 * @author Administrator
 *
 */
@Service("consumerCertificateWebServiceImpl")
public class MConsumerCertificateWebServiceImpl {
	/**
	 * 日志
	 */
	private Logger log = LoggerFactory.getLogger(this.getClass());
	//证件地址信息
	@Resource(name="certificateAddressBizImpl")
	private ICertificateAddressBiz certificateAddressBizImpl;
	//系统参数配置
	@Resource(name = "mBaseSystemConfigInfoServiceImpl")
	private IMBaseSystemConfigInfoService mBaseSystemConfigInfoServiceImpl;
	
	/** 跳转到证件上传界面**/
	public ViewAndModel certificate_index(ViewAndModel viewAndModel,Long consumer_id) {
		log.info("跳转到证件上传界面");
		// 如需在添加页需要加载元素在此处增加
		viewAndModel.setViewName("certificate/certificate_index");
		viewAndModel.addObject("consumer_id", consumer_id);
		return viewAndModel;
	}
	/** 跳转到证件上传界面**/
	public ViewAndModel certificate_toAdd(ViewAndModel viewAndModel,Long consumer_id) {
		log.info("跳转到证件上传界面");
		// 如需在添加页需要加载元素在此处增加
		viewAndModel.setViewName("certificate/addCertificate");
		viewAndModel.addObject("consumer_id", consumer_id);
		return viewAndModel;
	}
	/** 跳转到证件编辑界面**/
	public ViewAndModel certificate_toEdit(ViewAndModel viewAndModel,Long id) {
		log.info("跳转到证件上传界面");
		// 如需在添加页需要加载元素在此处增加
		viewAndModel.setViewName("certificate/editCertificate");
		MCertificateAddressVO addressVO = certificateAddressBizImpl.getCertificateAddressById(id).getObjVo();
		viewAndModel.addObject("addressVO", addressVO);
		return viewAndModel;
	}
	/** 保存图片信息**/
	public ResultBooleanVO certificate_save(MCertificateAddressForm form,MConsumerLoginVO loginConsumer) {
		log.info("保存证件图片信息form={}",form);
		form.setFile_nature(MConsumersNatures.PERSON);
		return certificateAddressBizImpl.saveConsumerCertificate(form,loginConsumer);
	}
	/** 更新图片信息**/
	public ResultBooleanVO certificate_update(MCertificateAddressForm form,MConsumerLoginVO loginConsumer) {
		log.info("保存证件图片信息form={}",form);
		return certificateAddressBizImpl.updateCertificate(form,loginConsumer);
	}
	/** 查询数据列表**/
	public ResultListVO<MCertificateAddressVO> certificate_page(MCertificateAddressForm form) {
		log.info("查询数据翻页信息form={}",form);
		ResultListVO<MCertificateAddressVO> result = certificateAddressBizImpl.queryPage(form);
		
		List<MCertificateAddressVO> list = result.getData();
		if (!list.isEmpty()) {
			set_file_url(list);
		}
		return result;
	}
	
	
	
	/***
     * 上传图片到服务器 并压缩
     *
     * @param myFile  文件
     * @param request
     * @return
     */
	public String UploadFile(MultipartFile myFile, HttpServletRequest request) {
		InputStream is = null;
        FileOutputStream fs = null;
        String filePath = null;
        /** 临时文件夹*/
        String imgPath = "xyimages" + File.separator + "buttonImgTemp" + File.separator;
        String tempPath = MSystemConstants.CERTIMAGEFACE_OLD_PATH + imgPath;
        System.out.println("old-path-" + tempPath);
        String name = myFile.getOriginalFilename();
        File oldFile = new File(tempPath);
        if (!oldFile.exists()) {
            oldFile.mkdirs();
        }
        /** 处理后文件夹*/
        String newImaPath = "xyimages" + File.separator + "buttonImg" + File.separator;
        String newPath = MSystemConstants.CERTIMAGEFACE_OLD_PATH + newImaPath;
        System.out.println("new-path-" + newPath);
        File newFile = new File(newPath);
        if (!newFile.exists()) {
            newFile.mkdirs();
        }
        try {
            /** 先存取源文件*/
            is = myFile.getInputStream();
            fs = new FileOutputStream(tempPath + myFile.getOriginalFilename());
            //...
            if (myFile.getSize() > 0) {
                byte[] buffer = new byte[1024 * 1024];
                int bytesum = 0;
                int byteread = 0;
                while ((byteread = is.read(buffer)) != -1) {
                    bytesum += byteread;
                    fs.write(buffer, 0, byteread);
                    fs.flush();
                }
                fs.close();
                is.close();
            }
            /** 处理源文件 ，进行压缩再放置到新的文件夹*/
            filePath = tempPath + myFile.getOriginalFilename();
            System.out.println("filePath:{}"+filePath);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return filePath;
    } 

	
	/***
     * 压缩制定大小图片
     *
     * @param oldPath  临时图片路径
     * @param copyPath 压缩图片保存路径
     * @param width    宽度
     * @param height   高度
     * @param quality  高清度
     * @return
     * @throws Exception
     */
    public static String zipWidthHeightImageFile(String oldPath, String copyPath, int width, int height, float quality) {
        Boolean sta = false;
        File oldFile = new File(oldPath);
        File newFile = new File(copyPath);
        String newFilePath = null;
        if (oldFile == null) {
            return null;
        }
        String newImage = null;
        try {
            /** 对服务器上的临时文件进行处理 */
            Image srcFile = ImageIO.read(oldFile);
            int w = srcFile.getWidth(null);
            System.out.println(w);
            int h = srcFile.getHeight(null);
            System.out.println(h);

            /** 宽,高设定 */
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(srcFile, 0, 0, width, height, null);
            //String filePrex = oldFile.substring(0, oldFile.indexOf('.'));
            /** 压缩后的文件名 */
            //newImage = filePrex + smallIcon+ oldFile.substring(filePrex.length());
            /** 压缩之后临时存放位置 */
            FileOutputStream out = new FileOutputStream(newFile);
            newFilePath = newFile.getPath();
           
            
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
            /** 压缩质量 */
            jep.setQuality(quality, true);
            encoder.encode(tag, jep);
            out.close();
            sta = true;
        } catch (Exception e) {
            e.printStackTrace();
            sta = false;
        }
        return newFilePath;
    }
	
	
	
	/** 上传图片到服务器**/
    public ResultUploadVO<String> upload(MultipartFile file, HttpServletRequest request) {
		String paths = null;
		String path = request.getSession().getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();
		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		try {
			file.transferTo(targetFile);
			//paths = OSSUtils.uploadFile(targetFile, MSystemConstants.CERTIFICATE_UPLOAD_URL_);
			boolean flag = targetFile.delete();
			if (null == paths) {
				return new ResultUploadVO<>("sj.m.common.upload.error");
			}
			log.info("上传文件成功，路径paths={},flag={} :" ,paths,flag);
		}catch (Exception e) {
			log.error("文件上传异常error={}",e);
		}
		ResultUploadVO<String> result = new ResultUploadVO<>();
		
		result.setSuccess(true);
		result.setMsgcode("sj.m.common.upload.success");
		result.setPath(paths);
		return result;
	}
	
	/**增加下载路径处理*/
	public void set_file_url(List<MCertificateAddressVO> list){
		String template_url= template_url();
		for(MCertificateAddressVO vo:list){
			if (null != vo) {
				vo.setFile_address(template_url+vo.getFile_address());
			}
		}
	}
	public String template_url() {
		MSystemConfigInfoForm form = new MSystemConfigInfoForm();
		form.setConfig_name(MSystemConstants.TEMPLATE_DOWNLOAD_URL);
		MSysConfigVO configVO = mBaseSystemConfigInfoServiceImpl.queryByIdSystemConfig(form).getObjVo();
		if(null==configVO) {
			return null;
		}
		return configVO.getConfig_value();
	}

}
